package com.five.admin.redis;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.five.pojo.vo.OrderDetailVO;
import com.five.pojo.vo.OrderListVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class OrderRedisCache {
    // Key前缀（修正列表Key为3个占位符）
    private static final String ORDER_LIST_KEY = "mobile:order:list:%s:%s:%s"; // userId:pageNum:pageSize
    private static final String ORDER_DETAIL_KEY = "mobile:order:detail:%s:%s"; // userId:orderNo
    private static final String ORDER_STATUS_KEY = "mobile:order:status:%s:%s"; // userId:orderNo

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    // 缓存订单列表（带pageSize）
    public void cacheOrderList(Long userId, Integer pageNum, Integer pageSize, Page<OrderListVO> list) {

        String key = String.format(ORDER_LIST_KEY, userId, pageNum, pageSize);
        log.info("[订单列表缓存] 缓存成功，key={}", key);
        redisTemplate.opsForValue().set(key, JSON.toJSONString(list), 30, TimeUnit.MINUTES);
    }

    // 获取缓存的订单列表
    public Page<OrderListVO> getCachedOrderList(Long userId, Integer pageNum, Integer pageSize) {
        String key = String.format(ORDER_LIST_KEY, userId, pageNum, pageSize);
        String jsonString = (String) redisTemplate.opsForValue().get(key);
        if (jsonString != null) {
            log.info("[订单列表缓存] 获取成功，key={}", key);
            return JSON.parseObject(jsonString, new TypeReference<Page<OrderListVO>>() {});
        }
        return null;
    }

    // 缓存订单详情
    public void cacheOrderDetail(Long userId, String orderNo, OrderDetailVO detail) {
        String key = String.format(ORDER_DETAIL_KEY, userId, orderNo);
        log.info("[订单详情缓存] 缓存成功，key={}", key);
        redisTemplate.opsForValue().set(key, JSON.toJSONString(detail), 1, TimeUnit.HOURS);
    }

    // 获取缓存的订单详情
    public OrderDetailVO getCachedOrderDetail(Long userId, String orderNo) {
        String key = String.format(ORDER_DETAIL_KEY, userId, orderNo);
        String jsonString = (String) redisTemplate.opsForValue().get(key);
        log.info("[订单详情缓存] 获取成功，key={}", key);
        return jsonString != null ? JSON.parseObject(jsonString, OrderDetailVO.class) : null;
    }

    // 缓存订单状态（存储为Integer，避免类型转换）
    public void cacheOrderStatus(Long userId, String orderNo, Integer status) {
        String key = String.format(ORDER_STATUS_KEY, userId, orderNo);
        log.info("[订单状态缓存] 缓存成功，key={}", key);
        redisTemplate.opsForValue().set(key, status, 5, TimeUnit.MINUTES); // 直接存Integer
    }

    // 获取订单状态（直接获取Integer）
    public Integer getCachedOrderStatus(Long userId, String orderNo) {
        String key = String.format(ORDER_STATUS_KEY, userId, orderNo);
        log.info("[订单状态缓存] 获取成功，key={}", key);
        return (Integer) redisTemplate.opsForValue().get(key); // 与存储类型一致
    }

    // 清除订单相关缓存（修复列表缓存清除逻辑）
    public void clearOrderCache(Long userId, String orderNo) {
        // 清除详情和状态缓存
        redisTemplate.delete(String.format(ORDER_DETAIL_KEY, userId, orderNo));
        redisTemplate.delete(String.format(ORDER_STATUS_KEY, userId, orderNo));
        log.info("[订单缓存] 清除成功，userId={}, orderNo={}", userId, orderNo);

        String listKeyPattern = "mobile:order:list:" + userId + ":*";
        Set<String> listKeys = redisTemplate.keys(listKeyPattern);
        log.info("[订单列表缓存] 清除成功，userId={}, pattern={}", userId, listKeyPattern);
        if (CollectionUtils.isNotEmpty(listKeys)) {
            redisTemplate.delete(listKeys);
        }
    }
}